#![allow(dead_code)]

use std::time::Duration;
use log::{error, info};
use std::default::Default;
use crate::api::account_info_request::get_account_info_list;
use crate::command::MyStruct;
use crate::config::CONFIG;
use crate::config::const_store::global_store;
use crate::entity::example_table_test::run_db_util_tests;
use crate::utils::TaskManager;
use crate::utils::http_client::{HttpClient, HttpContext};
//use tokio::time::{sleep};
use crate::utils::js_bridge::JsBridge;

pub fn test() {
    // loop_task();//重复任务
    // onec_task();//单次任务
    //modify_const_store();//维护常量池
    // test_call_js();//rust调用js
    // test_js_call_rust();//js调用rust
    // test_db_operations();//测试数据库操作
    // test_config();//测试配置

    // block_on_result_task_box();//测试block_on_result
    // block_on_task_box();//测试block_on
    // block_on_feature_task_box();
    account_info_list_block();
}

pub fn account_info_list_block(){
    TaskManager::global().spawn_once(|| {
        async move {
            let list = get_account_info_list().await.unwrap_or_default();

            // 现在list是Vec<AccountInfoListResp>类型
            for item in list {
                // 处理每个账户信息
                println!("账户: {:?}", item);
            }

            Ok(()) // 返回Result<(), Error>
        }
    });
}

pub fn block_on_result_task_box() {
    let result = block_on_result_task().unwrap_or_else(|e| {
        error!("【block_on_result】执行失败: {}", e);
        return Default::default();
    });

    info!("【block_on_result】结果:{:?}", result);
}

pub fn block_on_task_box() {
    let result = block_on_task().unwrap();
    info!("【block_on】结果:{:?}", result);
}
pub fn block_on_feature_task_box() {
    let result = block_on_feature_task().unwrap();
    info!("【block_on_feature_task】结果:{:?}", result);
}

pub fn block_on_task() -> Option<String> {
    let result: Option<String> = TaskManager::global().block_on(|| {
        tokio::spawn(async move {
            // 创建客户端并处理错误
            let client = match HttpClient::new(10) {
                Ok(client) => client,
                Err(e) => {
                    error!("创建客户端失败: {}", e);
                    return "".to_string(); // 返回空字符串，跳过后续请求
                }
            };
            let context = HttpContext::default();
            // 发送请求并处理错误
            let response = client.get("https://speed.daofengwangluo.com/realip", Some(context))
                .await
                .unwrap_or_else(|e| {
                    error!("请求失败: {:?}", e);
                    return "".to_string(); // 返回空字符串（String 类型）
                });

            info!("Response: {:?}", response);
            response // 返回 String
        })
    });
    result
}

pub fn block_on_result_task() -> Result<String, String> {
    let result: Result<String, String> = TaskManager::global().block_on_result(|| {
        tokio::spawn(async move {
            // 创建客户端并处理错误
            let client = HttpClient::new(10).map_err(|e| e.to_string())?;
            let context = HttpContext::default();

            // 发送请求并处理错误
            let response = client.get("https://speed.daofengwangluo.com/realip", Some(context))
                .await
                .map_err(|e| e.to_string())?;

            info!("Response: {:?}", response);
            Ok(response)
        })
    });

    result
}

pub fn block_on_feature_task() -> Result<String, String> {
    let result: Result<String, String> = TaskManager::global().block_on_future(async {
        // 创建客户端
        let client = match HttpClient::new(10) {
            Ok(client) => client,
            Err(e) => {
                error!("创建客户端失败: {:?}", e);
                return "".to_string(); // 返回空字符串或错误信息
            }
        };
        let context = HttpContext::default();

        // 发送请求
        let response = match client.get("https://speed.daofengwangluo.com/realip", Some(context)).await {
            Ok(response) => response,
            Err(e) => {
                error!("请求失败: {:?}", e);
                return "".to_string(); // 返回空字符串或错误信息
            }
        };

        info!("Response: {:?}", response);
        response // 返回 String
    })
        .ok_or_else(|| "任务执行失败或被取消".to_string());

    result
}

pub fn test_config() {
    log::info!("【测试配置】开始测试...");
    log::info!("【测试配置】当前配置api_url: {:?}", CONFIG.api_url);
    log::info!("【测试配置】当前配置api_url: {:?}", CONFIG.login_config);
}

pub fn test_db_operations() {
    TaskManager::global().spawn_once(|| {
        async move {
            log::info!("【任务1】正在执行数据库操作...");
            match run_db_util_tests().await {
                Ok(()) => log::info!("【数据库操作】成功完成"),
                Err(e) => log::error!("【数据库操作】失败: {}", e),
            }
            Ok(())
        }
    });
}

pub fn test_js_call_rust() {
    TaskManager::global().spawn_once(|| {
        async move {
            tokio::time::sleep(Duration::from_secs(10)).await;

            log::info!("【准备执行rust_js_rust命令】...");
            let script2 = "window.testJsCallRust";
            match JsBridge::async_func::<(), MyStruct>(script2, None, 3000).await {
                Ok(val) => log::info!("【执行js-rust】成功完成,结果:{:?}",val),
                Err(e) => log::error!("【执行js-rust】失败: {}", e),
            }
            Ok(())
        }
    });
}

pub fn test_call_js() {
    TaskManager::global().spawn_once(|| {
        async move {
            tokio::time::sleep(Duration::from_secs(5)).await;

            log::info!("【准备执行js1】...");
            let script1 = "1+2";
            match JsBridge::async_script::<i64>(script1, 1000).await {
                Ok(val) => log::info!("【执行js】成功完成,结果:{}",val),
                Err(e) => log::error!("【执行js】失败: {}", e),
            }

            log::info!("【准备执行js2】...");
            let script2 = "window.testJsBridge";
            let param: MyStruct = MyStruct {
                name: "张三".to_string(),
                age: 18,
            };
            match JsBridge::async_func::<MyStruct, MyStruct>(script2, Some(param), 3000).await {
                Ok(val) => log::info!("【执行js】成功完成,结果:{:?}",val),
                Err(e) => log::error!("【执行js】失败: {}", e),
            }

            Ok(())
        }
    });
}

fn modify_const_store() {
    log::info!("常量存储内容: {:?}", global_store().read());

    global_store().write().syn_zhcfg.syn_zh_interval = 30;
    global_store().write().syn_zhcfg.syn_zh_time = 0;

    log::info!("版本号为:{:?}", global_store().read().syn_zhcfg)
}

// ==== 示例任务 1：循环打印日志 ====
fn loop_task() {
    TaskManager::global().spawn_periodic(Duration::from_secs(30), || {
        async move {
            log::info!("【任务1】正在执行日志记录...");
            Ok(())
        }
    });
}

// ==== 示例任务 2：一次性任务 ====
fn onec_task() {
    TaskManager::global().spawn_once(|| {
        async move {
            log::info!("【任务2】开始获取网页数据...");
            // 创建不带拦截器的客户端
            let simple_client = HttpClient::new(10)?;

            // 使用带拦截器的客户端发送请求
            let mut context = HttpContext::default();

            // 添加自定义头
            HttpClient::add_custom_header(&mut context, "X-Custom-Header", "value");

            // 添加完整 Cookie 字符串
            //HttpClient::add_cookie(&mut context, "session_id=abc123; user_token=xyz789");

            let response = simple_client.get("https://speed.daofengwangluo.com/realip", Some(context)).await?;
            info!("Response: {:?}", response);
            // match simple_client.get_response("https://speed.daofengwangluo.com/realip", Some(context)).await {
            //     Ok(response) => {
            //         println!("Response: {:?}", response);
            //
            //         // 按需解析 Cookie
            //         let cookies = HttpClient::parse_cookies(&response);
            //         println!("Session cookie: {:?}", cookies.get("session_id"));
            //     }
            //     Err(e) => match e {
            //         HttpError::Reqwest(err) => eprintln!("Request error: {}", err),
            //         HttpError::Status(code, msg) => eprintln!("Status error: {} - {}", code, msg),
            //         HttpError::Custom(msg) => eprintln!("Custom error: {}", msg),
            //     },
            // }
            Ok(())
        }
    });
}